package com.espirit.util;

import java.io.IOException;

import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.impl.Indenter;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.ObjectWriter;
import org.codehaus.jackson.map.annotate.JsonSerialize.Inclusion;
import org.codehaus.jackson.util.DefaultPrettyPrinter;

public class CommonUtils {

	private CommonUtils() {

	}

	public static String objectToJSON(Object object) throws JsonGenerationException, JsonMappingException, IOException {
		String text = null;
		ObjectMapper mapper = new ObjectMapper();
		mapper.setSerializationConfig(mapper.getSerializationConfig()
				.withSerializationInclusion(Inclusion.NON_NULL)
				.withSerializationInclusion(Inclusion.NON_DEFAULT)
				.withSerializationInclusion(Inclusion.NON_EMPTY));
		ObjectWriter jsonWriter = mapper.writerWithDefaultPrettyPrinter();
		DefaultPrettyPrinter printer = new DefaultPrettyPrinter();
		printer.indentObjectsWith(new Indenter() {
			@Override
			public void writeIndentation(JsonGenerator jg, int level)
					throws IOException, JsonGenerationException {
				jg.writeRaw('\n');
				for (int i = 0; i < level; i++) {
					jg.writeRaw('\t');
				}
			}

			@Override
			public boolean isInline() {
				return false;
			}
		});
		jsonWriter = jsonWriter.withPrettyPrinter(printer);
		text = jsonWriter.writeValueAsString(object);

		return text;
	}
	
}
